#!/bin/bash	

if [ $# -ne 1 ]; then
    echo "Usage:  ./autest.sh parameter1"
    exit 1
fi

if ! command -v cargo &> /dev/null; then
    echo "== Download cargo"
	curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
fi

LOG_DIR="${HOME}/logs/stratovirt"
if [ ! -d ${LOG_DIR} ]; then
	echo "== Mkdir ${LOG_DIR}"
	mkdir ${LOG_DIR}
fi

PRO_DIR=$1
cd $1
PRO_DIR=$(pwd)
echo "== project directory is ${PRO_DIR}"
strato_path="${PRO_DIR}/stratovirt"
if [ ! -d "${strato_path}" ]; then
	echo "Clone stratovirt"
	cd $PRO_DIR
	git clone https://gitee.com/openeuler/stratovirt.git

	cd $strato_path
	sudo make build

	cargo build --workspace --bins --release
fi
export STRATOVIRT_BINARY=${strato_path}/target/release/stratovirt
echo "STRATOVIRT_BINARY is ${STRATOVIRT_BINARY}"

TEST_DIR="${PRO_DIR}/stratovirt/tests/mod_test"
cd ${TEST_DIR}
echo "entering $(pwd)"

cd tests
TABLE="${PRO_DIR}/table_stratovirt_mod.txt"
echo "| Test Name | Performance Name | Performance Value |" > ${TABLE}
echo "| --- | --- | --- |" >> ${TABLE}
for file in *_test.rs; do
	if [ -f "$file" ]; then
		file=$(echo "$file" | sed 's:.*/::')
		# grep -n "#\[test" $file | grep -o '^[0-9]\+' | awk '{print $1 + 1}' > ${LOG_DIR}/tmp.txt
		echo ""
		file=$(echo "$file" | sed 's:\.rs::')
		echo "== Now test ${file}"
		# ${PRO_DIR}/performance_counter_920.sh  "cargo test --test ${file}"  ${LOG_DIR} ${TABLE} ${file} 1>${LOG_DIR}/${file}_record_1.txt 2>${LOG_DIR}/${file}_record_2.txt
		${PRO_DIR}/perf_out.sh  "cargo test --test ${file}"  ${LOG_DIR} ${TABLE} ${file} &>${LOG_DIR}/${file}_record.txt

		# while IFS= read -r line; do
		# 	# 把line的内容作为行号，提取 ${file} 的对应行
		# 	test_name=$(sed "${line}q;d" ${file})	
		# 	echo ""
		# 	echo "== Now test ${file}"
		# 	file=$(echo "$file" | sed 's:\.rs::')
		# done < ${LOG_DIR}/tmp.txt
		# break
	fi
done

# echo "" > ${LOG_DIR}/record_1.txt
# echo "" > ${LOG_DIR}/record_2.txt
# TABLE="${PRO_DIR}/table_strato.txt"
# echo "| Test Name | Performance Name | Performance Value |" > ${TABLE}
# echo "| --- | --- | --- |" >> ${TABLE}
# while IFS= read -r line; do
# 	echo "== Now test $line"
# 	${PRO_DIR}/performance_counter_920.sh  "cargo test ${line}" ${LOG_DIR} ${TABLE} ${line} 1>>${LOG_DIR}/record_1.txt 2>>${LOG_DIR}/record_2.txt
# 	# break
# done < ${PRO_DIR}/test_names.txt

# ./performance_counter_920.sh "go test -v -run TestQueryRange" /home/cloud1/k8s/perf